package com.atguigu.gulimall.ware.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ配置类
 *
 * @author xiaoping
 * @create 2020/7/3 11:04
 * @since 1.0.0
 */
@Configuration
public class MyRabbitConfig {

    /**
     * 消息序列化json格式
     * @return
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

//    /**
//     * 监听普通队列，以便于快速创建如下队列，交换机信息
//     */
//    @RabbitListener(queues = "stock.release.stock.queue")
//    public void handle(Message message){
//
//    }


    /**
     * 创建主题交换机（一对多，包含模糊匹配）
     * @return
     */
    @Bean
    public Exchange stockEventExchange(){
        //TopicExchange(String name, boolean durable, boolean autoDelete, Map<String, Object> arguments)
        return new TopicExchange("stock-event-exchange",true,false);
    }

    /**
     * 创建普通队列
     */
    @Bean
    public Queue stockReleaseStockQueue(){
        return new Queue("stock.release.stock.queue", true,false , false);
    }

    /**
     * 创建延时队列
     */
    @Bean
    public Queue stockDelayQueue(){
        Map<String,Object> args = new HashMap<>();
        //设置死信路由交换机
        args.put("x-dead-letter-exchange", "stock-event-exchange");
        //路由键
        args.put("x-dead-letter-routing-key","stock.release");
        //过期时间(毫秒)
        args.put("x-message-ttl", 120000);
        return new Queue("stock.delay.queue", true,false , false,args);
    }

    /**
     * 普通队列绑定关系
     */
    @Bean
    public Binding stockReleaseBinding(){
        return new Binding("stock.release.stock.queue",Binding.DestinationType.QUEUE,"stock-event-exchange","stock.release.#",null);
    }

    /**
     * 延时队列绑定关系
     */
    @Bean
    public Binding stockLockedBinding(){
        return new Binding("stock.delay.queue",Binding.DestinationType.QUEUE,"stock-event-exchange","stock.locked",null);
    }


}
